<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use think\Controller;
use think\facade\Config;

# echo json
function Code($code=null,$msg=false,$data=false,$options=256){
    $array = [];
    $array["code"] = $code;
    (is_bool($msg) && !$msg) ? false : $array["msg"] = $msg;
    (is_bool($data) && !$data) ? false : $array["data"] = $data;
    echo json_encode($array, $options);
    exit();
}

class Common extends Controller{

    # 加密、解密方法  $string 需要加密文本 。$operation "D"为解密，E为加密
    private function encrypt($string,$operation,$key=null){
        if($key === null){
            $key = Config::get("app.tokenEncrypt");
        }
        $key=md5($key);
        $key_length=strlen($key);
        $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string;
        $string_length=strlen($string);
        $rndkey=$box=array();
        $result='';
        for($i=0;$i<=255;$i++){
            $rndkey[$i]=ord($key[$i%$key_length]);
            $box[$i]=$i;
        }
        for($j=$i=0;$i<256;$i++){
            $j=($j+$box[$i]+$rndkey[$i])%256;
            $tmp=$box[$i];
            $box[$i]=$box[$j];
            $box[$j]=$tmp;
        }
        for($a=$j=$i=0;$i<$string_length;$i++){
            $a=($a+1)%256;
            $j=($j+$box[$a])%256;
            $tmp=$box[$a];
            $box[$a]=$box[$j];
            $box[$j]=$tmp;
            $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256]));
        }
        if($operation=='D'){
            if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8)){
                return substr($result,8);
            }else{
                return'';
            }
        }else{
            return str_replace('=','',base64_encode($result));
        }
    }

    # 生成Token
    protected function MakeToken($array){
        // 需要的值: aid、是否为七天登录、时间戳
        $string = json_encode($array,256);
        return $this->encrypt($string,"E")."d2";
    }

    # 检查token
    # 检查token
    protected function CheckToken($string){
        $str = substr($string,-2);
        if($str === "d2"){
            $new_str = substr($string,0,strlen($string)-2);
            $info = $this->encrypt($new_str,"D");
            $user = json_decode($info,true);
            if(isset($user["time"]) && isset($user["aid"])){
                $time = $user["time"];
                if($time+60*60*24*7 < time()){
                    # token过期
                    Code(901, "身份验证已过期，请重新登录");
                }else{
                    $admin = db("admin")->where("aid",$user["aid"])->find();
                    if(empty($admin)){
                        # 管理员不存在，token违法
                        Code(801, "非法身份登录");
                    }else{
                        return [
                            "aid" => $user["aid"]
                        ];
                    }
                }
            }else{
                # token违法
                Code(801, "非法身份登录");
            }
        }else{
            # token违法
            Code(801, "非法身份登录");
        }
        return false;
    }

}
